using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EntityManager : MonoBehaviour
{
    //缓存所有实体的集合
    Dictionary<string, GameObject> entities = new Dictionary<string, GameObject>();

    //所有实体分组的集合
    Dictionary<string, Transform> entityGroups = new Dictionary<string, Transform>();

    private Transform entityParent;

    private void Awake()
    {
        entityParent = this.transform.parent.Find("Entity");
    }

    //设置实体对象分组
    public void SetEntityGroup(List<string> _groups)
    {
        for(int i = 0; i < _groups.Count; i++) 
        {
            GameObject group = new GameObject("Group-" + _groups[i]);
            group.transform.SetParent(entityParent, false);
            entityGroups[_groups[i]] = group.transform; 
        }
    }

    //获取对应的实体分组对象
    public Transform GetEntityGroup(string _groupName)
    {
        if(!entityGroups.ContainsKey(_groupName)) 
        {
            Debug.LogError("The entity group is not exist:" + _groupName);
            return null;
        }

        return entityGroups[_groupName];
    }

    //
    public void ShowEntity(string _name, string _group, string _luaName)
    {
        GameObject entity = null;

        if(entities.TryGetValue(_name, out entity)) 
        {
            EntityLogic logic = entity.GetComponent<EntityLogic>();
            logic.OnShow();
        }

        Manager.Resources.LoadModelPrefab(_name, (UnityEngine.Object obj) =>
        {
            entity = Instantiate(obj) as GameObject;
            Transform parent = GetEntityGroup(_group);
            entity.transform.SetParent(parent, false);
            entities.Add(_name, entity);
            EntityLogic entityLogic = entity.AddComponent<EntityLogic>();
            entityLogic.Init(_luaName);
            entityLogic.OnShow();
        });
    }
}
